﻿using AutoMapper;
using commodity.Dtos;
using commodity.Models;
using commodity.Services;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Threading.Tasks;

namespace commodity.Controllers
{
    [Route("api/[controller]")]
    [ApiController]
    public class GoodsController : ControllerBase
    {
        private ICommodityRepository _commodity;
        private IMapper _mapper;
        private IHttpContextAccessor _httpContextAccessor;
        public GoodsController(ICommodityRepository commodity, IMapper mapper,IHttpContextAccessor httpContextAccessor)
        {
            _commodity = commodity;
            _mapper = mapper;
            _httpContextAccessor = httpContextAccessor;
        }
        [HttpGet]
        [Authorize]
        public async Task<ReturnJson> GetGoods([FromQuery] GetGoodsDto getGoodsDto)
        {
            IEnumerable<GoodsDto> goods = _mapper.Map<IEnumerable<GoodsDto>>(await _commodity.GetGoods(getGoodsDto));
            if ((goods.Count()) <= 0)
            {
                return new ReturnJson
                {
                    Data = null,
                    Status = 404,
                    Message = "数据不存在"
                };
            }
            return new ReturnJson
            {
                Data = new { data = goods, total = await _commodity.GetGoodsTotal(), pagenum = getGoodsDto.Pagenum },
                Status = 200,
                Message = "获取数据成功"
            };
        }
        [HttpOptions("{goodId}")]
        public IActionResult OptionsbyId()
        {
            return Ok();
        }
        [HttpDelete("{goodId}")]
        public async Task<ReturnJson> DeleteGoodsByGoodId([FromRoute] int goodId)
        {
            if (!(await _commodity.DeleteGoodsByGoodId(goodId)))
            {
                return new ReturnJson
                {
                    Status = 400,
                    Data = null,
                    Message = "删除失败"
                };
            }
            if (!(await _commodity.SaveAsync()))
            {
                return new ReturnJson
                {
                    Status = 400,
                    Data = null,
                    Message = "删除失败"
                };
            }
            return new ReturnJson
            {
                Status = 200,
                Data = null,
                Message = "删除成功"
            };
        }
        [HttpOptions("File")]
        public IActionResult OptionFile()
        {
            return Ok();
        }

        [HttpPost("File")]
        [Authorize]
        public async Task<ReturnJson> AddFile([FromForm] IFormFile file)
        {
            if (file != null)
            {
                string uploadsFolder = Path.GetFullPath("./Images");
                string uniqueFilePath = Guid.NewGuid().ToString() + "_" + file.FileName;
                string filePath = Path.Combine(uploadsFolder, uniqueFilePath);
                using (FileStream fileStream = new FileStream(filePath, FileMode.Create, FileAccess.Write))
                {
                    await file.CopyToAsync(fileStream);
                }
                return new ReturnJson
                {
                    Status = 200,
                    Message = "上传成功",
                    Data = uniqueFilePath
                };
            }
            return new ReturnJson
            {
                Status = 400,
                Message = "上传失败",
                Data = null
            };
        }
        [HttpDelete("File/{fileName}")]
        [Authorize]
        public Task<ReturnJson> DeleteFile([FromRoute] string fileName) 
        {
            string uploadsFolder = Path.GetFullPath("./Images");
            string filePath = Path.Combine(uploadsFolder, fileName);
            return Task.Run(() =>
            {
                System.IO.File.Delete(filePath);
                return new ReturnJson { 
                Data=null,
                Status=200,
                Message="删除成功"
                };

            });
        }
        [HttpOptions]
        public IActionResult Options() 
        {
            return Ok();
        }
        [HttpPost]
        public async Task<ReturnJson> AddGoods([FromBody] object data) 
        {
            
            AddGoodsDto add = JsonConvert.DeserializeObject<AddGoodsDto>(data.ToString());
            
            
            Goods goods = _mapper.Map<Goods>(add);
            if (await _commodity.AddGoods(goods)) 
            {
                return new ReturnJson
                {
                    Status = 200,
                    Data = null,
                    Message = "添加成功"
                };
            }
            return new ReturnJson
            {
                Status = 404,
                Data = null,
                Message = "添加失败"
            };
        }
    }
}
